<template>
  <div class="class-management-container">
    <el-card class="content" v-loading="loading">
      <!-- 班级基本信息 -->
      <div class="class-header">
        <el-button link type="primary" icon="ArrowLeft" @click="goBack">返回</el-button>
        <h2>{{ classInfo.className }} 班级详情</h2>
        <div class="class-meta">
          <span>班级ID: {{ classInfo.id }}</span>
          <span>学生人数: {{ students.length }}人</span>
          <span>创建时间: {{ formatDate(classInfo.createTime) }}</span>
        </div>
      </div>

      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
        <el-tab-pane label="班级学生" name="students">
          <div class="action-bar">
            <el-button 
              type="primary" 
              @click="showAddStudentDialog"
              :disabled="!classInfo.hasPermission"
            >
              <el-icon><Plus /></el-icon>
              添加学生
            </el-button>
          </div>
          
          <el-table :data="students" border style="width: 100%" v-loading="tabLoading">
            <el-table-column label="学号" width="120">
              <template #default="{row}">
                <div class="boxed-cell">
                  {{ row.id }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="姓名" width="120">
              <template #default="{row}">
                <div class="boxed-cell">
                  {{ row.stuName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="stuScore" label="积分" width="100" sortable>
              <template #default="{row}">
                <el-tag :type="getScoreTagType(row.stuScore)">
                  {{ row.stuScore }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="stuStudyTime" label="学习时长(分)" width="120" sortable></el-table-column>
            <el-table-column prop="clock" label="打卡时间" width="120"></el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  @click="removeStudent(scope.row)"
                  :disabled="!classInfo.hasPermission"
                >
                  <el-icon><Delete /></el-icon>
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="班级教师" name="teachers">
          <el-table :data="teachers" border style="width: 100%" v-loading="tabLoading">
            <el-table-column prop="id" label="工号" width="120"></el-table-column>
            <el-table-column prop="teaName" label="教师姓名" width="120"></el-table-column>
            <el-table-column prop="coursNum" label="授课数量" width="100" sortable></el-table-column>
            <el-table-column label="职称" width="120">
              <template #default="{row}">
                {{ getTeacherTitle(row.teaName) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="班级课程" name="courses">
          <el-table :data="courses" border style="width: 100%" v-loading="tabLoading">
            <el-table-column prop="courseId" label="课程ID" width="100"></el-table-column>
            <el-table-column prop="courseName" label="课程名称" width="150"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加学生对话框 -->
    <el-dialog 
      v-model="addStudentDialogVisible" 
      title="添加学生到班级" 
      width="60%"
      top="5vh"
      :close-on-click-modal="false" 
    >
      <div class="dialog-content">
        <el-input
          v-model="studentSearch"
          placeholder="输入学生姓名或学号搜索"
          clearable
          style="width: 300px; margin-bottom: 20px;"
          @input="filterStudents"
        />
        
        <el-table 
          :data="pagedFilteredStudents" 
          border 
          style="width: 100%"
          v-loading="studentLoading"
          height="50vh"
          @selection-change="handleSelectionChange"
        >
          <el-table-column 
            type="selection" 
            width="55"
            :selectable="checkSelectable"
          ></el-table-column>
          
          <el-table-column label="学号" width="120">
            <template #default="{row}">
              <div class="boxed-cell">
                {{ row.id }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="姓名" width="120">
            <template #default="{row}">
              <div class="boxed-cell">
                {{ row.stuName }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="{row}">
              <el-tag v-if="isStudentInClass(row.id)" type="success">已添加</el-tag>
              <el-tag v-else type="info">未添加</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="filteredStudents.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <span class="selected-count">已选择 {{ selectedStudents.length }} 名学生</span>
          <div>
            <el-button @click="addStudentDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="batchAddStudents"
              :disabled="selectedStudents.length === 0"
            >
              确认添加
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { ArrowLeft, Plus, Delete } from '@element-plus/icons-vue'
import { classApi } from '@/api/class'
import { studentApi } from '@/api/students'
import { teacherApi } from '@/api/teacher'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 状态管理
const loading = ref(false)
const tabLoading = ref(false)
const studentLoading = ref(false)
const addStudentDialogVisible = ref(false)
const studentSearch = ref('')
const allStudents = ref([])
const filteredStudents = ref([])
const selectedStudents = ref([])
const activeTab = ref('students')
const students = ref([])
const teachers = ref([])
const courses = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(15)

// 班级信息
const classInfo = reactive({
  id: route.params.id || '',
  className: '',
  classStuNum: 0,
  createTime: '',
  teacherId: null,
  hasPermission: false
})

// 计算属性 - 分页后的学生数据
const pagedFilteredStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredStudents.value.slice(start, end)
})

// 初始化班级数据
const initializeClassData = () => {
  const routeState = route.state || {}
  const incomingData = routeState.classData || {}
  
  Object.assign(classInfo, {
    ...incomingData,
    id: route.params.id || incomingData.id
  })

  // 如果没有路由状态，尝试从本地存储恢复权限
  if (!routeState.classData) {
    recoverPermission()
  }
}

// 恢复权限 - 从API重新验证
const recoverPermission = async () => {
  try {
    if (!authStore.userId || !classInfo.id) return
    
    // 1. 获取教师ID
    const teacherRes = await teacherApi.getTeacherByUid(authStore.userId)
    const teacherId = teacherRes.data?.id || teacherRes.id
    if (!teacherId) return
    
    // 2. 验证权限
    const permissionRes = await classApi.checkTeacherClass(teacherId, classInfo.id)
    classInfo.hasPermission = Boolean(permissionRes?.data ?? permissionRes)
    classInfo.teacherId = teacherId
    
  } catch (error) {
    console.error('恢复权限失败:', error)
    classInfo.hasPermission = false
  }
}

// 加载班级详情
const loadClassDetail = async () => {
  try {
    loading.value = true
    initializeClassData()
    
    const res = await classApi.getClassDetail(classInfo.id)
    if (res?.data) {
      Object.assign(classInfo, res.data.classInfo)
      students.value = res.data.students || []
      teachers.value = res.data.teachers || []
      courses.value = res.data.courses || []
    }
  } catch (error) {
    console.error('加载班级详情失败:', error)
    ElMessage.error('加载失败')
    router.push('/class/list')
  } finally {
    loading.value = false
  }
}

// 加载标签页数据
const loadTabData = async (tabName) => {
  try {
    tabLoading.value = true
    const classId = route.params.id
    if (!classId) throw new Error('缺少班级ID')
    
    switch (tabName) {
      case 'students':
        students.value = (await classApi.getClassStudents(classId))?.data || []
        break
      case 'teachers':
        teachers.value = (await classApi.getClassTeachers(classId))?.data || []
        break
      case 'courses':
        courses.value = (await classApi.getClassCourses(classId))?.data || []
        break
    }
  } catch (error) {
    ElMessage.error(`加载${tabName}数据失败: ${error.message}`)
  } finally {
    tabLoading.value = false
  }
}

// 显示添加学生对话框
const showAddStudentDialog = async () => {
  if (!classInfo.hasPermission) {
    ElMessage.warning('无添加权限')
    return
  }
  
  try {
    studentLoading.value = true
    addStudentDialogVisible.value = true
    currentPage.value = 1 // 重置页码
    allStudents.value = (await studentApi.getAllStudents()) || []
    filteredStudents.value = [...allStudents.value]
    await nextTick()
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error(error)
  } finally {
    studentLoading.value = false
  }
}

// 辅助函数
const handleSelectionChange = (selection) => (selectedStudents.value = selection)
const checkSelectable = (row) => !students.value.some(s => s.id === row.id)
const isStudentInClass = (studentId) => students.value.some(s => s.id === studentId)
const filterStudents = () => {
  filteredStudents.value = studentSearch.value 
    ? allStudents.value.filter(s => 
        s.stuName.toLowerCase().includes(studentSearch.value.toLowerCase()) ||
        String(s.userId).includes(studentSearch.value)
      )
    : [...allStudents.value]
  currentPage.value = 1 // 搜索后重置页码
}

// 批量添加学生
const batchAddStudents = async () => {
  if (!selectedStudents.value.length) return ElMessage.warning('请选择学生')
  
  const loadingInstance = ElLoading.service({ text: '添加中...' })
  try {
    const results = await Promise.allSettled(
      selectedStudents.value.map(s => studentApi.addStudentToClass(classInfo.id, s.id))
    )
    const successCount = results.filter(r => r.status === 'fulfilled').length
    successCount && (ElMessage.success(`添加${successCount}人`), loadTabData('students'))
  } catch (error) {
    ElMessage.error('添加失败')
    console.error(error)
  } finally {
    loadingInstance.close()
    addStudentDialogVisible.value = false
    selectedStudents.value = []
  }
}

// 工具函数
const formatDate = (date) => date && new Date(date).toLocaleString('zh-CN', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit'
}).replace(/\//g, '-')

const getScoreTagType = (score) => score >= 90 ? 'success' : score >= 80 ? 'primary' : score >= 60 ? 'warning' : 'danger'
const getTeacherTitle = (name) => name.includes('教授') ? '教授' : name.includes('副教授') ? '副教授' : name.includes('讲师') ? '讲师' : '教师'
const getTeacherName = (id) => teachers.value.find(t => t.id === id)?.teaName || '未知'

// 事件处理
const handleTabChange = (tab) => loadTabData(tab.paneName)
const removeStudent = async (s) => {
  if (!classInfo.hasPermission) {
    ElMessage.warning('无权限移除学生')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要移除学生 ${s.stuName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await studentApi.removeStudentFromClass(classInfo.id, s.id)
    students.value = students.value.filter(stu => stu.id !== s.id)
    ElMessage.success('移除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败')
      console.error(error)
    }
  }
}
const goBack = () => router.push('/class/list')

// 生命周期
onMounted(() => {
  initializeClassData()
  loadClassDetail()
})

watch(() => route.params.id, (newId) => {
  if (newId) {
    classInfo.id = newId
    loadClassDetail()
  }
}, { immediate: true })
</script>

<style scoped>
.class-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.content {
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.class-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.class-header h2 {
  margin: 10px 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
  font-weight: 600;
}

.class-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.action-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tabs__content) {
  padding: 0 10px;
}

.el-table {
  margin-top: 15px;
  font-size: 14px;
}

.el-tag {
  margin: 2px;
  font-size: 14px;
}

.dialog-content {
  padding: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-top: 10px;
  border-top: 1px solid var(--el-border-color-light);
}

.selected-count {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.boxed-cell {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 6px 10px;
  display: inline-block;
  min-width: 60px;
  text-align: center;
  background-color: #f5f7fa;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整按钮大小 */
:deep(.el-button) {
  font-size: 14px;
  padding: 8px 15px;
}

/* 调整标签页样式 */
:deep(.el-tabs__item) {
  font-size: 14px;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
}

/* 调整对话框样式 */
:deep(.el-dialog) {
  border-radius: 6px;
}

:deep(.el-dialog__header) {
  padding: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 15px;
}

:deep(.el-dialog__footer) {
  padding: 10px 15px;
}
</style>